<html lang="en-US">

<head>
    
<title>「连载七」让你的服务同时提供 HTTP 接口 - 花落雨忧</title>

<meta property="og:title" content="「连载七」让你的服务同时提供 HTTP 接口 - 花落雨忧">



    



    
    <meta property="description" content="接口需要提供给其他业务组访问，但是 RPC 协议不同无法内调，对方问能否走 HTTP 接口，怎么办？
[&amp;hellip;] 微信（公众号、小程序）等第三方回调接口只支持 HTTP 接口，怎么办
[&amp;hellip;] 我相信你在实际工作中都会遇到如上问题，在 gRPC 中都是有解决方案的，本章节将会进行介绍 🤔
[&amp;hellip;] 关键一点，gRPC 的协议是基于 HTTP/2 的，因此应用程序能 &amp;hellip;">
    <meta property="og:description" content="接口需要提供给其他业务组访问，但是 RPC 协议不同无法内调，对方问能否走 HTTP 接口，怎么办？
[&amp;hellip;] 微信（公众号、小程序）等第三方回调接口只支持 HTTP 接口，怎么办
[&amp;hellip;] 我相信你在实际工作中都会遇到如上问题，在 gRPC 中都是有解决方案的，本章节将会进行介绍 🤔
[&amp;hellip;] 关键一点，gRPC 的协议是基于 HTTP/2 的，因此应用程序能 &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.asia/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.asia/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.asia/js/jquery.min.js"></script>




<link href="https://www.lican.asia/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>

        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/posts/go/grpc/2018-10-12-grpc-http/">「连载七」让你的服务同时提供 HTTP 接口</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2018/10/12</a>
                                            
                                            
                                            
                                            By 
                                            <a class="author" href="javascript:;">煎鱼</a></div>
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <h2 id="前言">前言</h2>
<ul>
<li>
<p>接口需要提供给其他业务组访问，但是 RPC 协议不同无法内调，对方问能否走 HTTP 接口，怎么办？</p>
</li>
<li>
<p>微信（公众号、小程序）等第三方回调接口只支持 HTTP 接口，怎么办</p>
</li>
</ul>
<p>我相信你在实际工作中都会遇到如上问题，在 gRPC 中都是有解决方案的，本章节将会进行介绍 🤔</p>
<h2 id="为什么可以同时提供-http-接口">为什么可以同时提供 HTTP 接口</h2>
<p>关键一点，gRPC 的协议是基于 HTTP/2 的，因此应用程序能够在单个 TCP 端口上提供 HTTP/1.1 和 gRPC 接口服务（两种不同的流量）</p>
<h2 id="怎么同时提供-http-接口">怎么同时提供 HTTP 接口</h2>
<h3 id="检测协议">检测协议</h3>
<pre tabindex="0"><code>if r.ProtoMajor == 2 &amp;&amp; strings.Contains(r.Header.Get(&#34;Content-Type&#34;), &#34;application/grpc&#34;) {
    server.ServeHTTP(w, r)
} else {
    mux.ServeHTTP(w, r)
}
</code></pre><h3 id="流程">流程</h3>
<ol>
<li>检测请求协议是否为 HTTP/2</li>
<li>判断 Content-Type 是否为 application/grpc（gRPC 的默认标识位）</li>
<li>根据协议的不同转发到不同的服务处理</li>
</ol>
<h2 id="grpc">gRPC</h2>
<h3 id="tls">TLS</h3>
<p>在前面的章节，为了便于展示因此没有简单封装</p>
<p>在本节需复用代码，重新封装了，可详见：<a href="https://github.com/EDDYCJY/go-grpc-example/tree/master/pkg/gtls">go-grpc-example</a></p>
<h3 id="目录结构">目录结构</h3>
<p>新建 simple_http_client、simple_http_server 目录，目录结构如下：</p>
<pre tabindex="0"><code>go-grpc-example
├── client
│   ├── simple_client
│   ├── simple_http_client
│   └── stream_client
├── conf
├── pkg
│   └── gtls
├── proto
├── server
│   ├── simple_http_server
│   ├── simple_server
│   └── stream_server
</code></pre><h3 id="server">Server</h3>
<p>在 simple_http_server 目录下新建 server.go，写入文件内容：</p>
<pre tabindex="0"><code>package main

import (
	&#34;context&#34;
	&#34;log&#34;
	&#34;net/http&#34;
	&#34;strings&#34;

	&#34;github.com/EDDYCJY/go-grpc-example/pkg/gtls&#34;
	pb &#34;github.com/EDDYCJY/go-grpc-example/proto&#34;

	&#34;google.golang.org/grpc&#34;
)

type SearchService struct{}

func (s *SearchService) Search(ctx context.Context, r *pb.SearchRequest) (*pb.SearchResponse, error) {
	return &amp;pb.SearchResponse{Response: r.GetRequest() + &#34; HTTP Server&#34;}, nil
}

const PORT = &#34;9003&#34;

func main() {
	certFile := &#34;../../conf/server/server.pem&#34;
	keyFile := &#34;../../conf/server/server.key&#34;
	tlsServer := gtls.Server{
		CertFile: certFile,
		KeyFile:  keyFile,
	}

	c, err := tlsServer.GetTLSCredentials()
	if err != nil {
		log.Fatalf(&#34;tlsServer.GetTLSCredentials err: %v&#34;, err)
	}

	mux := GetHTTPServeMux()

	server := grpc.NewServer(grpc.Creds(c))
	pb.RegisterSearchServiceServer(server, &amp;SearchService{})

	http.ListenAndServeTLS(&#34;:&#34;+PORT,
		certFile,
		keyFile,
		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.ProtoMajor == 2 &amp;&amp; strings.Contains(r.Header.Get(&#34;Content-Type&#34;), &#34;application/grpc&#34;) {
				server.ServeHTTP(w, r)
			} else {
				mux.ServeHTTP(w, r)
			}

			return
		}),
	)
}

func GetHTTPServeMux() *http.ServeMux {
	mux := http.NewServeMux()
	mux.HandleFunc(&#34;/&#34;, func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(&#34;eddycjy: go-grpc-example&#34;))
	})

	return mux
}
</code></pre><ul>
<li>http.NewServeMux：创建一个新的 ServeMux，ServeMux 本质上是一个路由表。它默认实现了 ServeHTTP，因此返回 Handler 后可直接通过 HandleFunc 注册 pattern 和处理逻辑的方法</li>
<li>http.ListenAndServeTLS：可简单的理解为提供监听 HTTPS 服务的方法，重点的协议判断转发，也在这里面</li>
</ul>
<p>其实，你理解后就会觉得很简单，核心步骤：判断 -&gt; 转发 -&gt; 响应。我们改变了前两步的默认逻辑，仅此而已</p>
<h3 id="client">Client</h3>
<p>在 simple_http_server 目录下新建 client.go，写入文件内容：</p>
<pre tabindex="0"><code>package main

import (
	&#34;context&#34;
	&#34;log&#34;

	&#34;google.golang.org/grpc&#34;

	&#34;github.com/EDDYCJY/go-grpc-example/pkg/gtls&#34;
	pb &#34;github.com/EDDYCJY/go-grpc-example/proto&#34;
)

const PORT = &#34;9003&#34;

func main() {
	tlsClient := gtls.Client{
		ServerName: &#34;go-grpc-example&#34;,
		CertFile:   &#34;../../conf/server/server.pem&#34;,
	}
	c, err := tlsClient.GetTLSCredentials()
	if err != nil {
		log.Fatalf(&#34;tlsClient.GetTLSCredentials err: %v&#34;, err)
	}

	conn, err := grpc.Dial(&#34;:&#34;+PORT, grpc.WithTransportCredentials(c))
	if err != nil {
		log.Fatalf(&#34;grpc.Dial err: %v&#34;, err)
	}
	defer conn.Close()

	client := pb.NewSearchServiceClient(conn)
	resp, err := client.Search(context.Background(), &amp;pb.SearchRequest{
		Request: &#34;gRPC&#34;,
	})
	if err != nil {
		log.Fatalf(&#34;client.Search err: %v&#34;, err)
	}

	log.Printf(&#34;resp: %s&#34;, resp.GetResponse())
}
</code></pre><h2 id="验证">验证</h2>
<h3 id="grpc-client">gRPC Client</h3>
<pre tabindex="0"><code>$ go run client.go 
2018/10/04 14:56:56 resp: gRPC HTTP Server
</code></pre><h3 id="http11-访问">HTTP/1.1 访问</h3>
<p><img src="https://image.eddycjy.com/1d92cb9e949e32eef7f8a64a6a77deb9.jpg" alt="image"></p>
<h2 id="总结">总结</h2>
<p>通过本章节，表面上完成了同端口提供双服务的功能，但实际上，应该是加深了 HTTP/2 的理解和使用，这才是本质</p>
<h2 id="拓展">拓展</h2>
<p>如果你有一个需求，是要<strong>同时提供</strong> RPC 和 RESTful JSON API 两种接口的，不要犹豫，点进去：<a href="https://segmentfault.com/a/1190000013339403">gRPC + gRPC Gateway 实践</a></p>
<h2 id="问题">问题</h2>
<p>你以为这个方案就万能了吗，不。Envoy Proxy 的支持就不完美，无法同时监听一个端口的两种流量 😤</p>
<h2 id="参考">参考</h2>
<h3 id="本系列示例代码">本系列示例代码</h3>
<ul>
<li><a href="https://github.com/EDDYCJY/go-grpc-example">go-grpc-example</a></li>
</ul>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc/2018-10-10-interceptor/">「连载六」Unary and Stream interceptor</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc/2018-10-08-ca-tls/">「连载五」基于 CA 的 TLS 证书认证</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc/2018-10-07-grpc-tls/">「连载四」TLS 证书认证</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc/2018-09-24-stream-client-server/">「连载三」gRPC Streaming, Client and Server</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/grpc/2018-09-23-client-and-server/">「连载二」gRPC Client and Server</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            <li>
                                                <a href="/tags/grpc" title="View all posts tagged match">grpc</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.asia/posts/posts/go/grpc/2018-10-10-interceptor/"
                                                    rel="prev">「连载六」Unary and Stream interceptor</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.asia/posts/posts/go/grpc/2018-10-14-per-rpc-credentials/">「连载八」对 RPC 方法做自定义认证</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.asia/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    <section id="qrcode" class="widget widget_media_image">
        <h2 class="widget-title">微信公众号</h2>
        <img width="258" height="258"
            src="https://www.lican.asia/wechat/lican.png"
            class="image wp-image-5514  attachment-full size-full" alt=""
            style="max-width: 100%; height: auto;"
            sizes="(max-width: 258px) 100vw, 258px">
    </section>
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.asia All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>